<template>
  <div class="flex justify-content align mt-16">
   <div 
      @mouseenter="handleMouseEnter" 
      @mouseleave="handleMouseLeave" 
      style="position: relative; width: 1200px; height: 300px; overflow: hidden;"
    >
      <img ref="image" 
           src="@/assets/lottie/homePage/lottie2.png" 
           alt=""
           style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;transform: scale(.834);" />
      <div ref="lottieContainer" 
           style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
      </div>
      <div ref="clickableBox"
           @click="handleOpenChat"
           style="position: absolute; bottom:55px; right:160px; width: 94px; height: 46px; cursor: pointer;">
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onBeforeUnmount} from 'vue';
import lottie from 'lottie-web';
import animationData from '@/assets/lottie/homePage/tab05_1080P.json';
import EventBus from "@/utils/eventBus.js";
onBeforeUnmount(()=>{
	if (animationInstance) {
		animationInstance.destroy(); // 销毁动画实例
	}
})
const lottieContainer = ref(null);
	const image = ref(null);
	const clickableBox = ref(null);
	let animationInstance = null;
let isInner = false
	const startAnimation = () => { 
		image.value.style.opacity = '0';
		lottieContainer.value.style.opacity = '1';
		if(!animationInstance){
			animationInstance = lottie.loadAnimation({
				container: lottieContainer.value,
				renderer: 'svg',
				loop: false,
				autoplay: true,
				animationData: animationData
			});
		}
    isInner = true
		 // animationInstance.addEventListener('complete', callback); // 监听动画播放完成事件
		 animationInstance.playSegments([0, 60], true);
	};
    
	const stopAnimation = () => {
		if (animationInstance) {
			animationInstance.destroy(); // 销毁动画实例
		}

		image.value.style.opacity = '1';
		lottieContainer.value.style.opacity = '0';
	};

	const handleMouseEnter = () => {
		startAnimation();
	};

	const handleMouseLeave = () => {
    isInner = false

		    animationInstance.addEventListener('complete', callback); // 监听动画播放完成事件
			animationInstance.playSegments([60, 113], true);
		// stopAnimation();
	};
	const callback = (e) => {
		if(!image.value)return;
		animationInstance.removeEventListener('complete', callback); // 监听动画播放完成事件
		if (!isInner) {
    
		image.value.style.opacity = '1';
		lottieContainer.value.style.opacity = '0';
    }
	}
const handleOpenChat = () => {
		EventBus.emit("openCustomerChat", {
			message: '您好, 我想了解更多关于网站优化的内容',
		});
	};
	
</script>

<style lang="scss" scoped>
</style>
